/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.data.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import edu.cmu.lti.sepia.data.resource.ResourceManager;
import edu.cmu.lti.sepia.infra.system.model.Log;

/**
 * 
 * Manages Log object in a DB.
 * 
 * @see Log
 * @author Hideki Shima
 *
 */
public class LogDAO {
	
	public static List<Log> getLogs( SQL sql ) throws SQLException {
		String query = Query.generate( Query.GET_LOGS, "" );
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ResultSet rs = null;
		List<Log> logs = new ArrayList<Log>();
		
		rs = sql.executeSelect(ps);
		if ( rs == null ) System.out.println( ps );
		while ( rs.next() ) logs.add( rsToObject(rs) );

		rs.close();
		ps.close();

		return logs;
	}
	
	public static String addLog( SQL sql, Log log ) throws SQLException {
		if (ResourceManager.debugMode) return "[Debug Mode] Skipped logging "+log.toString();
		
		String query = Query.generate( Query.ADD_LOG, "" );
		
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ps.setString(1, log.getDate());
		ps.setInt(2, log.getTaskId());
		ps.setInt(3, log.getUserId());
		ps.setString(4, log.getHost());
		ps.setString(5, log.getLogEvent());
		ps.setString(6, log.getDetail());			
		sql.executeInSilence(ps);
		ps.close();
		return "Successfully added "+log.toString();
	}

	private static Log rsToObject( ResultSet rs ) throws SQLException {
		Log log = new Log( rs.getInt(1), rs.getString(2), 
				rs.getInt(3), rs.getInt(4),
				rs.getString(5), rs.getString(6), rs.getString(7) );
		return log;
	}
}
